#!/usr/bin/env python
# coding: utf-8

import urllib
import logging
import wsgiref.handlers
from google.appengine.api import urlfetch
from google.appengine.api import users
import minjson as json
import cPickle as pickle 
from pyamf.remoting.gateway.wsgi import WSGIGateway
from google.appengine.ext import db
from edamame import Edamame

def translate(keyword , langpair):
    encoding = 'utf-8'
    query = {'q': keyword.encode(encoding),
         'langpair': langpair,
         'v' : '1.0'
        }
    url = "http://ajax.googleapis.com/ajax/services/language/translate?" + urllib.urlencode(query)
    logging.debug("creating UserPrefs object for user %s", url)
    result = urlfetch.fetch(url)
    obj = json.read(result.content)
    return obj

def imagesSearch(keyword):
    # security problem
    encoding = 'utf-8'
    query = {'q': keyword.encode(encoding),
             'v' : '1.0',
             'rsz':'large'
             }
    url = "http://ajax.googleapis.com/ajax/services/search/images?" + urllib.urlencode(query)
    result = urlfetch.fetch(url)
    obj = json.read(result.content)
    return obj

def webSearch(keyword):
    # security problem
    encoding = 'utf-8'
    query = {'q': keyword.encode(encoding),
             'v' : '1.0',
             'rsz':'large'
              }
    
    url = "http://ajax.googleapis.com/ajax/services/search/web?" + urllib.urlencode(query)
    result = urlfetch.fetch(url)
    obj = json.read(result.content)
    
    return obj

def loadEdamame(id):
    try:
        edamame = Edamame.get_by_id(int(id))
        if(edamame is not None):
            return edamame.content
        else:
            return "<edamame/>"
    except Exception, inst:
        return inst + " "

def saveEdamame(id,title,comment,data):
   edamame = Edamame.get_by_id(int(id))
   if edamame.author and ( edamame.author != users.get_current_user()):
       return "<reponce status='ng'/>"
   if(edamame is not None):
        edamame.content = data 
        edamame.title = title
        edamame.comment = comment
        edamame.put()
        return "<reponce status='ok'/>"
   return "<reponce status='ng'/>"  

services = {
    'googleservice.websearch': webSearch,
    'googleservice.imagessearch': imagesSearch,
    'googleservice.translate': translate,
    'saveEdamame': saveEdamame,
    'loadEdamame': loadEdamame
}

def main():
    application = WSGIGateway(services)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
